import 'dart:async';

import 'package:dio/dio.dart';
import 'package:kasax/engine/network/base_resp.dart';
import 'package:kasax/engine/network/interceptors/normal_interceptor.dart';

/// DIO管理器
class DioManager {
  static DioManager _instance = DioManager._internal();

  factory DioManager() => _instance;

  static DioManager getInstance() => _instance;

  late Dio _dio;

  static BaseOptions _options =
  BaseOptions(connectTimeout: 30 * 1000, receiveTimeout: 30 * 1000);

  DioManager._internal() {
    _dio = Dio(_options);
    List<Interceptor> list = [];
    list.add(NormalInterceptor());
    _dio.interceptors.addAll(list);
  }

  /// 使用自定义的配置配置options
  static config({String baseUrl = "", BaseOptions? options}) {
    if (baseUrl != null) {
      _options.baseUrl = baseUrl;
    }
    if (options != null) {
      _options = options;
    }
  }

  /// get请求
  /// 调用之前先配置baseurl
  Future<dynamic> get(path, {params, bool autoConvert = true}) async {
    Response response;
    if (params != null) {
      response = await _dio.get(path, queryParameters: params);
    } else {
      response = await _dio.get(path);
    }
    if (response != null) {
      if (autoConvert) {
        return BaseResp.fromJson(response.data);
      } else {
        return response.data;
      }
    } else {
      var compiler = Completer();
      var f = compiler.future;
      compiler.complete(true);
      return f;
    }
  }

  /// post请求
  /// 调用之前先配置baseurl
  Future<dynamic> post(path,
      {Map<String, dynamic>? queryParameters,
        Map<String, dynamic>? data,
        bool autoConvert = true}) async {
    Response response;
    if (queryParameters != null && data != null) {
      response =
      await _dio.post(path, queryParameters: queryParameters, data: data);
    } else if (queryParameters != null && data == null) {
      response = await _dio.post(path, queryParameters: queryParameters);
    } else if (queryParameters == null && data != null) {
      response = await _dio.post(path, data: data);
    } else {
      response = await _dio.post(path);
    }
    if (response != null) {
      if (autoConvert) {
        return BaseResp.fromJson(response.data);
      } else {
        return response.data;
      }
    } else {
      var compiler = Completer();
      var f = compiler.future;
      compiler.complete(true);
      return f;
    }
  }
}
